import os
import json
from pathlib import Path
from typing import Dict, List, Optional, Any
from dataclasses import dataclass, asdict


@dataclass
class TranslationPreset:
    """翻译预设配置"""
    name: str
    description: str = ""
    source_language: str = "English"
    target_language: str = "Chinese"
    custom_prompt: str = ""
    enabled: bool = True


class ConfigManager:
    """配置管理器"""
    
    def __init__(self, config_dir: Optional[str] = None):
        if config_dir is None:
            # 使用系统的默认配置目录
            self.config_dir = Path.home() / ".config" / "ollama_translate"
        else:
            self.config_dir = Path(config_dir)
        
        self.config_dir.mkdir(parents=True, exist_ok=True)
        self.config_file = self.config_dir / "config.json"
        self.presets_file = self.config_dir / "presets.json"
        
        # 默认配置
        self.default_config = {
            "last_used_preset": "",
            "auto_save": True,
            "theme": "latte",
            "window_size": [800, 600],
            "recent_files": [],
            "font_family": "System Default",
            "font_size": 12,
            "streaming_translation": True,
            "selected_model": ""
        }
        
        # Cappuccin color schemes
        self.themes = {
            "latte": {
                "name": "Cappuccino Latte",
                "background": "#eff1f5",
                "foreground": "#4c4f69",
                "primary": "#1e66f5",
                "secondary": "#e6e9ef",
                "accent": "#ea76cb",
                "text_edit_bg": "#ffffff",
                "text_edit_fg": "#4c4f69",
                "button_bg": "#1e66f5",
                "button_fg": "#ffffff",
                "group_bg": "#e6e9ef",
                "group_border": "#bcc0cc"
            },
            "frappe": {
                "name": "Cappuccino Frappe",
                "background": "#303446",
                "foreground": "#c6d0f5",
                "primary": "#8caaee",
                "secondary": "#292c3c",
                "accent": "#f4b8e4",
                "text_edit_bg": "#232634",
                "text_edit_fg": "#c6d0f5",
                "button_bg": "#8caaee",
                "button_fg": "#303446",
                "group_bg": "#292c3c",
                "group_border": "#51576d"
            },
            "macchiato": {
                "name": "Cappuccino Macchiato",
                "background": "#24273a",
                "foreground": "#cad3f5",
                "primary": "#8aadf4",
                "secondary": "#1e2030",
                "accent": "#f5bde6",
                "text_edit_bg": "#181926",
                "text_edit_fg": "#cad3f5",
                "button_bg": "#8aadf4",
                "button_fg": "#24273a",
                "group_bg": "#1e2030",
                "group_border": "#494d64"
            },
            "mocha": {
                "name": "Cappuccino Mocha",
                "background": "#1e1e2e",
                "foreground": "#cdd6f4",
                "primary": "#89b4fa",
                "secondary": "#181825",
                "accent": "#f5c2e7",
                "text_edit_bg": "#11111b",
                "text_edit_fg": "#cdd6f4",
                "button_bg": "#89b4fa",
                "button_fg": "#1e1e2e",
                "group_bg": "#181825",
                "group_border": "#45475a"
            }
        }
        
        # Font options
        self.font_families = [
            "System Default",
            "Arial",
            "Helvetica", 
            "Times New Roman",
            "Courier New",
            "Monospace",
            "DejaVu Sans",
            "Noto Sans",
            "Roboto"
        ]
        
        # 默认预设
        self.default_presets = [
            TranslationPreset(
                name="casual",
                description="轻松随意的语气翻译",
                source_language="English",
                target_language="Chinese",
                custom_prompt="请用轻松、自然的语气翻译以下内容，保持口语化的风格。"
            ),
            TranslationPreset(
                name="formal_letter",
                description="正式信件翻译",
                source_language="English", 
                target_language="Chinese",
                custom_prompt="请用正式、礼貌的语气翻译以下内容，适合商务信件或正式场合使用。"
            ),
            TranslationPreset(
                name="biology",
                description="生物学专业翻译",
                source_language="English",
                target_language="Chinese", 
                custom_prompt="请专业地翻译以下生物学相关内容，准确使用专业术语和科学表达。"
            )
        ]
        
        self.config = self.load_config()
        self.presets = self.load_presets()
    
    def load_config(self) -> Dict[str, Any]:
        """加载配置文件"""
        if self.config_file.exists():
            try:
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    config = json.load(f)
                    # 合并默认配置
                    for key, value in self.default_config.items():
                        if key not in config:
                            config[key] = value
                    return config
            except Exception as e:
                print(f"Error loading config: {e}")
        
        # 如果文件不存在或加载失败，返回默认配置
        return self.default_config.copy()
    
    def save_config(self):
        """保存配置文件"""
        try:
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(self.config, f, ensure_ascii=False, indent=2)
        except Exception as e:
            print(f"Error saving config: {e}")
    
    def load_presets(self) -> List[TranslationPreset]:
        """加载预设配置"""
        if self.presets_file.exists():
            try:
                with open(self.presets_file, 'r', encoding='utf-8') as f:
                    presets_data = json.load(f)
                    return [TranslationPreset(**preset) for preset in presets_data]
            except Exception as e:
                print(f"Error loading presets: {e}")
        
        # 如果文件不存在或加载失败，返回默认预设
        return self.default_presets.copy()
    
    def save_presets(self):
        """保存预设配置"""
        try:
            with open(self.presets_file, 'w', encoding='utf-8') as f:
                presets_data = [asdict(preset) for preset in self.presets]
                json.dump(presets_data, f, ensure_ascii=False, indent=2)
        except Exception as e:
            print(f"Error saving presets: {e}")
    
    def get_preset(self, name: str) -> Optional[TranslationPreset]:
        """根据名称获取预设"""
        for preset in self.presets:
            if preset.name == name:
                return preset
        return None
    
    def add_preset(self, preset: TranslationPreset):
        """添加新预设"""
        # 检查是否已存在同名预设
        for i, existing_preset in enumerate(self.presets):
            if existing_preset.name == preset.name:
                self.presets[i] = preset  # 更新现有预设
                break
        else:
            self.presets.append(preset)  # 添加新预设
        
        self.save_presets()
    
    def delete_preset(self, name: str):
        """删除预设"""
        self.presets = [preset for preset in self.presets if preset.name != name]
        self.save_presets()
    
    def get_preset_names(self) -> List[str]:
        """获取所有预设名称"""
        return [preset.name for preset in self.presets if preset.enabled]
    
    def update_config(self, key: str, value: Any):
        """更新配置"""
        self.config[key] = value
        self.save_config()
    
    def get_config_path(self) -> str:
        """获取配置目录路径"""
        return str(self.config_dir)
    
    def get_current_theme(self) -> Dict[str, str]:
        """获取当前主题配置"""
        theme_name = self.config.get("theme", "latte")
        return self.themes.get(theme_name, self.themes["latte"])
    
    def set_theme(self, theme_name: str):
        """设置主题"""
        if theme_name in self.themes:
            self.config["theme"] = theme_name
            self.save_config()
    
    def get_available_themes(self) -> Dict[str, Dict[str, str]]:
        """获取所有可用主题"""
        return self.themes
    
    def get_current_theme_name(self) -> str:
        """获取当前主题名称"""
        return self.config.get("theme", "latte")
    
    def get_font_family(self) -> str:
        """获取字体家族"""
        return self.config.get("font_family", "System Default")
    
    def get_font_size(self) -> int:
        """获取字体大小"""
        return self.config.get("font_size", 12)
    
    def get_streaming_enabled(self) -> bool:
        """获取流式翻译是否启用"""
        return self.config.get("streaming_translation", True)
    
    def get_selected_model(self) -> str:
        """获取选中的模型"""
        return self.config.get("selected_model", "")
    
    def set_font_family(self, font_family: str):
        """设置字体家族"""
        self.config["font_family"] = font_family
        self.save_config()
    
    def set_font_size(self, font_size: int):
        """设置字体大小"""
        self.config["font_size"] = font_size
        self.save_config()
    
    def set_streaming_enabled(self, enabled: bool):
        """设置流式翻译启用状态"""
        self.config["streaming_translation"] = enabled
        self.save_config()
    
    def set_selected_model(self, model: str):
        """设置选中的模型"""
        self.config["selected_model"] = model
        self.save_config()
    
    def get_available_fonts(self) -> list:
        """获取可用字体列表"""
        return self.font_families


# 全局配置管理器实例
_config_manager: Optional[ConfigManager] = None


def get_config_manager() -> ConfigManager:
    """获取全局配置管理器"""
    global _config_manager
    if _config_manager is None:
        _config_manager = ConfigManager()
    return _config_manager